//
//  ProductPictList.m
//  Trading365
//
//  Created by Jason on 12-3-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ProductPictList.h"
#import "ProductTakePict.h"
#import "ImageListCell.h"
#import "ImageLoader.h"
#import "InfoImageView.h"
#import "HttpServerURL.h"
#import "RoundedRectImageCreater.h"


@implementation ProductPictList
@synthesize table;
@synthesize productID;

static UIImage *imageData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = INFO_STRING_PRODUCT_PICTURE_LIST;
    
    //search,new
    UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 45, 45)]; 
    UIImage* imageBar = [UIImage imageNamed:PIC_MAIL_TOP_BAR];    

    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [tools respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [tools setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
        [tools setBackgroundImage:imageBar forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    }
    NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];    
    UIBarButtonItem *anotherButton1 = [[UIBarButtonItem alloc] 
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
                                       target:self 
                                       action:@selector(picture)]; 
    [buttons addObject:anotherButton1]; 
    [anotherButton1 release]; 

    [tools setItems:buttons animated:NO]; 
    [buttons release]; 
    UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithCustomView:tools]; 
    self.navigationItem.rightBarButtonItem = myBtn;
    [myBtn release]; 
    [tools release];
    
    imageData = [UIImage imageNamed:PIC_INFO_DEFAULT_PRODUCT];

    [self refreshData];
    [self.table reloadData];

}

- (void)viewWillAppear:(BOOL)animated {
	
    if ([[InfoType share] GetFlagFreshView] == INFO_TYPE_VIEW_REFRESH ){
        [NSTimer scheduledTimerWithTimeInterval:TIME_INTERVAL_FOR_PIC_LIST target:self selector:@selector(reflash) userInfo:nil repeats:NO];
        [[InfoType share] SetFlagFreshView:INFO_TYPE_VIEW_NOFRESH]; 
    }
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    productID = nil;
    
}

- (void)dealloc {
    [imageData release];
    
    [imgView release];
    [productID release];
    [table release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - Table View
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"ImageListCell";
    
    ImageListCell* cell = (ImageListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"ImageListCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];

    NSMutableDictionary *tmp_dictionary = nil;
    if ([responseParams count] <= indexPath.row){
        tmp_dictionary = [[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:indexPath.row]];
    }else{
        tmp_dictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    }

//    cell.picture.image = [UIImage imageNamed:PIC_INFO_DEFAULT_PRODUCT];

    cell.picture.image = imageData;

    NSString *imageURL =[[NSString alloc]initWithFormat:@"%@%@%@",[HttpServerURL GetInstance].serverImgUrl,[tmp_dictionary objectForKey:@"id"],[HttpServerURL GetInstance].serverIconUrlExt];
    [[ImageLoader sharedLoader] setImageWithURL:imageURL toView:cell.picture];
    [imageURL release];
    
    cell.name.text = [tmp_dictionary objectForKey:@"file_name"];
    [tmp_dictionary release];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;    

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *tmp_dictionary=nil;
    if (indexPath.row < [responseParams count]){
        tmp_dictionary=[[NSMutableDictionary alloc] initWithDictionary:[responseParams objectAtIndex:indexPath.row]];
    }else{
        tmp_dictionary=[[NSMutableDictionary alloc] initWithCapacity:0];
    }
    NSString *img_url=[[NSString alloc]initWithFormat:@"%@%@",[HttpServerURL GetInstance].serverImgUrl,[tmp_dictionary objectForKey:@"id"]];
    
    imgView = [[InfoImageView alloc] init];
    imgView.imageParams = responseParams;
    [imgView setShowNum:indexPath.row];
    imgView._sImageURL = img_url;
    imgView._sTitle = [tmp_dictionary objectForKey:@"file_name"];;
    imgView._sDes = @"";
    
    [imgView viewWillAppear:YES];
    [self.view addSubview:imgView.view];
    [imgView viewDidAppear:YES];
    
//    [imgView release];
    [img_url release];
    [tmp_dictionary release];
}


#pragma mark - my fun
-(void)refreshData
{    
    //    NSLog(@"InfoList refreshData.");
    [[[TaskManager Share] GetTaskByType:GetProductPictList Delegate:self] Excute];
}

-(void) getMoreData
{
    //    NSLog(@"InfoList getMoreData.");
    [[[TaskManager Share] GetTaskByType:GetProductPictList Delegate:self] Excute];
}


-(void) DoInBackground
{
    if (getflag == NO && _isSearching == NO) {
        return;
    }
    
    startRow = [responseParams count];
    NSString *num = [[NSString alloc] initWithFormat:@"%i",startRow];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    NSMutableArray *tmp=nil;
    XmlRpc *xml = [[XmlRpc alloc] init];
    
    //产品信息
    tmp = [xml GetProductPictureList:self.productID startRows:num rowsPerPage:rowsperpage];
    
    for (NSMutableDictionary* itq in tmp) {
        [responseParams addObject:itq];
    }

    if ([tmp count]<PER_PAGE_ROWS) {
        getflag = NO;
        _isSearching=NO;
    }
    
    [xml release];
    [num release];
    
    [self.table reloadData];

}


- (void)doSearch{
    [super doSearch];
    
    //
}

-(void)picture
{
    if ([[InfoType share] IsSimulator])
        return;

    ProductTakePict *picture = [[ProductTakePict alloc] init];
    [picture setBusinessID:productID];
    [picture setBusinessType:@"021"];//FileBusinessType021	FileBusinessType	021	产品图片
    [picture setMyTitle:@"添加产品图片"];
    [picture setFlagCameraPhotos:0];
    [picture initPictureBeginBlcok:^(NSDictionary *imgInfo,int typeFlag) {
        UIImage *newImage0 = [RoundedRectImageCreater createRoundedRectImage:[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size: [[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size] ];
        if (typeFlag == 0){
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage scale:1.0 orientation:UIImageOrientationRight];
        }else{
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage];
        }
        
    }];
    [self.navigationController pushViewController:picture animated:YES];
    
    [picture release];
}

-(void)find
{
    [searchDisplayController.searchBar setSelectedScopeButtonIndex:0];
    [searchDisplayController setActive:YES animated:YES];    
}

-(void) reflash
{
    [responseParams removeAllObjects];
    getflag = YES;
    _isSearching = YES;
    [self refreshData];
    [self.table reloadData];
}

@end
